<script setup>
import { ref, onMounted, nextTick } from "vue";
import {
  queryPageApi,
  queryDeptListApi,
  queryRoleListApi,
  addApi,
  queryByIdApi,
  updateApi,
  deleteApi,
} from "@/api/user";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Plus,
  Edit,
  Delete,
  Refresh,
  Upload,
} from "@element-plus/icons-vue";

// 钩子函数，页面加载完毕后执行
const token = ref("");
onMounted(() => {
  getDeptList();
  getRoleList();
  search();

  //获取token
  token.value = localStorage.getItem("token");
});

// 查询参数
const queryParams = ref({
  name: "",
  phone: "",
  deptId: "",
  status: "",
  page: 1,
  pageSize: 10,
});

// 表格数据
const userList = ref([]);
const total = ref(0);

// 部门列表
const deptList = ref([]);

// 角色列表
const roleList = ref([]);

// 选中的用户ID列表（用于批量删除）
const selectedUserIds = ref([]);

// 对话框相关
const formTitle = ref("");
const dialogFormVisible = ref(false);
const formLabelWidth = "100px";

// 用户表单数据
const user = ref({
  username: "",
  password: "",
  name: "",
  phone: "",
  email: "",
  gender: "",
  status: "",
  deptId: "",
  roleId: "",
  image: "",
  remark: "",
});

// 表单引用
const userFormRef = ref(null);

// 表单验证规则
const rules = ref({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "请输入2-20个字符", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "用户名只能包含字母、数字和下划线",
      trigger: "blur",
    },
  ],
  name: [
    { required: true, message: "姓名不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "请输入2-20个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { min: 5, max: 50, message: "请输入5-50个字符", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  deptId: [{ required: false, message: "请选择部门", trigger: "change" }],
  roleId: [{ required: false, message: "请选择角色", trigger: "change" }],
  remark: [{ max: 50, message: "备注不能超过50个字符", trigger: "blur" }],
});

// 搜索
const search = async () => {
  try {
    const result = await queryPageApi(queryParams.value);
    if (result.code === 1) {
      userList.value = result.data.rows;
      total.value = result.data.total;
    } else {
      ElMessage.error(result.msg || "获取数据失败");
      userList.value = [];
      total.value = 0;
    }
  } catch (error) {
    ElMessage.error("网络请求失败");
    userList.value = [];
    total.value = 0;
  }
};

// 清空
const clear = () => {
  queryParams.value = {
    name: "",
    phone: "",
    deptId: "",
    status: "",
    page: 1,
    pageSize: 10,
  };
  search();
};

// 获取部门列表
const getDeptList = async () => {
  try {
    const result = await queryDeptListApi();
    if (result.code === 1) {
      deptList.value = result.data;
    }
  } catch (error) {
    // 静默处理错误，不影响主要功能
  }
};

// 获取角色列表
const getRoleList = async () => {
  try {
    const result = await queryRoleListApi();
    if (result.code === 1) {
      roleList.value = result.data;
    }
  } catch (error) {
    // 静默处理错误，不影响主要功能
  }
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  queryParams.value.page = 1;
  search();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.page = val;
  search();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedUserIds.value = selection.map((item) => item.id);
};

// 添加用户
const handleAdd = () => {
  dialogFormVisible.value = true;
  formTitle.value = "新增用户";
  user.value = {
    username: "",
    password: "",
    name: "",
    phone: "",
    email: "",
    gender: "",
    status: "",
    deptId: "",
    roleId: "",
    image: "",
    remark: "",
  };

  // 延迟重置表单，确保DOM更新完成
  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.resetFields();
    }
  });
};

// 修改用户
const handleEdit = async (id) => {
  try {
    const result = await queryByIdApi(id);
    if (result.code === 1) {
      dialogFormVisible.value = true;
      formTitle.value = "修改用户";
      user.value = { ...result.data };
      // 确保部门ID和角色ID是数字类型
      if (user.value.deptId) user.value.deptId = Number(user.value.deptId);
      if (user.value.roleId) user.value.roleId = Number(user.value.roleId);
      if (user.value.gender) user.value.gender = Number(user.value.gender);
      if (user.value.status) user.value.status = Number(user.value.status);
    } else {
      ElMessage.error(result.msg || "获取用户信息失败");
    }
  } catch (error) {
    ElMessage.error("网络请求失败");
  }
};

// 对话框关闭时的清理
const handleDialogClose = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
  user.value = {
    username: "",
    password: "",
    name: "",
    phone: "",
    email: "",
    gender: "",
    status: "",
    deptId: "",
    roleId: "",
    image: "",
    remark: "",
  };
};

// 保存用户
const save = async () => {
  try {
    // 检查表单引用是否存在
    if (!userFormRef.value) {
      ElMessage.error("表单引用不存在");
      return;
    }

    const valid = await userFormRef.value.validate();

    if (valid) {
      // 准备提交的数据
      const submitData = { ...user.value };

      // 确保部门ID和角色ID是数字类型
      if (submitData.deptId) submitData.deptId = Number(submitData.deptId);
      if (submitData.roleId) submitData.roleId = Number(submitData.roleId);

      // 确保性别和状态是数字类型
      if (submitData.gender) submitData.gender = Number(submitData.gender);
      if (submitData.status) submitData.status = Number(submitData.status);

      let result;
      if (submitData.id) {
        // 修改用户
        result = await updateApi(submitData);
      } else {
        // 添加用户
        // 设置默认密码
        submitData.password = submitData.username + "123";
        result = await addApi(submitData);
      }

      if (result.code === 1) {
        ElMessage.success(submitData.id ? "修改成功" : "添加成功");
        dialogFormVisible.value = false;
        // 刷新列表
        search();
      } else {
        ElMessage.error(result.msg || "操作失败");
      }
    } else {
      ElMessage.error("请填写正确的数据");
    }
  } catch (error) {
    if (error.response && error.response.data) {
      ElMessage.error(
        `请求失败: ${error.response.data.message || error.response.data}`
      );
    } else if (error.message) {
      ElMessage.error(`错误: ${error.message}`);
    } else {
      ElMessage.error("网络请求失败");
    }
  }
};

// 删除用户
const handleDelete = async (id) => {
  ElMessageBox.confirm("您确定要删除该用户吗？", "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const result = await deleteApi(id);

        if (result.code === 1) {
          ElMessage.success("删除成功！");
          search();
        } else {
          ElMessage.error(result.msg || "删除失败");
        }
      } catch (error) {
        ElMessage.error("网络请求失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUserIds.value.length === 0) {
    ElMessage.warning("请选择要删除的用户");
    return;
  }

  ElMessageBox.confirm(
    `您确定要删除选中的 ${selectedUserIds.value.length} 个用户吗？`,
    "提示",
    {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const ids = selectedUserIds.value.join(",");
        const result = await deleteApi(ids);

        if (result.code === 1) {
          ElMessage.success("批量删除成功！");
          selectedUserIds.value = [];
          search();
        } else {
          ElMessage.error(result.msg || "批量删除失败");
        }
      } catch (error) {
        ElMessage.error("网络请求失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 文件上传前的处理 - 校验文件
const beforeUpload = (file) => {
  const isImage =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/jpg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("上传头像图片只能是 PNG/JPG/JPEG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 文件上传成功
const handleUploadSuccess = (response) => {
  if (response.code === 1) {
    user.value.image = response.data;
    ElMessage.success("上传成功");
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};

// 性别显示
const getGenderText = (gender) => {
  return gender === 1 ? "男" : gender === 2 ? "女" : "未知";
};

// 状态显示
const getStatusText = (status) => {
  return status === 1 ? "正常" : "停用";
};

// 状态样式
const getStatusType = (status) => {
  return status === 1 ? "success" : "danger";
};
</script>

<template>
  <div class="user">
    <!-- 搜索区域 -->
    <el-form
      :inline="true"
      :model="queryParams"
      ref="queryForm"
      class="search-form"
    >
      <el-form-item label="姓名">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="部门">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option label="正常" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search"
          ><el-icon><Search /></el-icon>搜索</el-button
        >
        <el-button @click="clear"
          ><el-icon><Refresh /></el-icon>清空</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd"
        ><el-icon><Plus /></el-icon>添加用户</el-button
      >
      <el-button
        type="danger"
        @click="handleBatchDelete"
        :disabled="selectedUserIds.length === 0"
      >
        <el-icon><Delete /></el-icon>批量删除
        <span v-if="selectedUserIds.length > 0"
          >({{ selectedUserIds.length }})</span
        >
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="userList"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
      highlight-current-row
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="name" label="姓名" width="120" align="center" />
      <el-table-column
        prop="username"
        label="用户名"
        width="120"
        align="center"
      />
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <el-avatar :size="40" :src="scope.row.image" :alt="scope.row.name">
            {{ scope.row.name?.charAt(0) }}
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        prop="deptName"
        label="部门"
        width="120"
        align="center"
      />
      <el-table-column
        prop="roleName"
        label="角色"
        width="120"
        align="center"
      />
      <el-table-column prop="phone" label="手机号" width="130" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="updateTime"
        label="最后操作时间"
        width="180"
        align="center"
      />
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)">
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="formTitle"
      v-model="dialogFormVisible"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="user"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="user.username" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="user.phone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select
                v-model="user.gender"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="user.deptId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="dept in deptList"
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 右列 -->
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="user.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="user.status"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
              <el-select
                v-model="user.roleId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.name"
                  :value="role.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action="/api/upload"
            name="image"
            :headers="{ token: token }"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          >
            <img v-if="user.image" :src="user.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            图片上传,支持扩展名: .png/.jpg/.jpeg 大小限制: 2M
          </div>
        </el-form-item>

        <!-- 备注说明 -->
        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="user.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入用户的备注信息,最多50字"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px;
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  min-width: 200px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

:deep(.el-avatar) {
  background-color: #409eff;
  color: #fff;
  font-weight: bold;
}

/* 表格选择样式 */
:deep(.el-table__row.current-row > td) {
  background-color: #f0f9ff;
}

/* 操作按钮样式 */
:deep(.el-button--link) {
  padding: 4px 8px;
}

:deep(.el-button--link:hover) {
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 头像上传样式 */
.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.4;
}
</style>
